<template>
  <a-modal
    :title="title"
    :open="visible"
    @cancel="handleCancel"
    @ok="handleOk"
    width="600px"
    :confirmLoading="submitLoading"
  >
    <a-spin :spinning="loading">
      <SchemaForm ref="formRef" v-bind="formProps" />
    </a-spin>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, computed, nextTick, watch } from 'vue';
import { message } from 'ant-design-vue';
import { useForm } from '@/components/core/schema-form';
import { createContact, updateContact } from '@/api/apis/customer';
import { cityOptions } from '@/data/city';

const props = defineProps<{
  visible: boolean;
  customerId?: string;
  contact?: any;
}>();

const emit = defineEmits<{
  'update:visible': [value: boolean];
  'success': [];
}>();

// 计算标题
const title = computed(() => props.contact?.id ? '编辑联系人' : '新增联系人');

// 加载状态
const loading = ref(false);
const submitLoading = ref(false);

// 表单字段配置
const formSchemas = [
  {
    field: 'name',
    label: '姓名',
    component: 'Input',
    required: true,
    rules: [{ required: true, message: '请输入联系人姓名', trigger: ['blur', 'change'] }],
    componentProps: {
      placeholder: '请输入联系人姓名'
    }
  },
  {
    field: 'phone',
    label: '电话',
    component: 'Input',
    required: true,
    rules: [
      { required: true, message: '请输入联系电话', trigger: ['blur', 'change'] },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: ['blur', 'change'] }
    ],
    componentProps: {
      placeholder: '请输入联系电话'
    }
  },
  {
    field: 'position',
    label: '职位',
    component: 'Input',
    componentProps: {
      placeholder: '请输入职位'
    }
  },
  {
    field: 'region',
    label: '所在地区',
    component: 'Cascader',
    componentProps: ({ formModel }) => ({
      options: cityOptions,
      placeholder: '请选择省市',
      changeOnSelect: true,
      onChange: (value) => {
        if (value?.length === 2) {
          const currentAddress = formModel.address || '';
          const newPrefix = String(value[0]) + String(value[1]);
          
          // 只有当地址为空时才自动添加省市前缀
          if (!currentAddress) {
            formModel.address = newPrefix;
          }
        }
      }
    }),
    rules: [
      {
        required: false,
        type: 'array',
        message: '请选择所在地区',
        validator: (_, value) => {
          if (value && value.length > 0 && value.length < 2) {
            return Promise.reject('请选择省份和城市');
          }
          return Promise.resolve();
        },
      },
    ],
  },
  {
    field: 'address',
    label: '详细地址',
    component: 'InputTextArea',
    componentProps: {
      rows: 2,
      placeholder: '请输入详细地址'
    }
  },
  {
    field: 'email',
    label: '邮箱',
    component: 'Input',
    rules: [
      { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ],
    componentProps: {
      placeholder: '请输入邮箱地址（选填）'
    }
  },
  {
    field: 'gender',
    label: '性别',
    component: 'RadioGroup',
    defaultValue: 0,
    required: true,
    rules: [{ required: true, type: 'number', message: '请选择性别', trigger: 'change' }],
    componentProps: {
      options: [
        { label: '男', value: 0 },
        { label: '女', value: 1 },
      ],
    },
  },
  {
    field: 'isPrimary',
    label: '是否主要联系人',
    component: 'Switch',
    defaultValue: false,
  },
];

// 表单配置
const formProps = {
  schemas: formSchemas,
  labelWidth: 100,
  baseColProps: { span: 24 },
  showActionButtonGroup: false,
  autoSubmitOnChange: false,
  submitOnReset: false,
};

// 使用表单
const [SchemaForm, formRef] = useForm(formProps);

// 监听visible变化，重置或填充表单
watch(() => props.visible, (newVisible) => {
  if (newVisible) {
    if (props.contact?.id) {
      // 编辑模式，填充数据
      nextTick(() => {
        const formData = { ...props.contact };
        if (formData.province && formData.city) {
          formData.region = [formData.province, formData.city];
        }
        formRef.value?.setFieldsValue(formData);
      });
    } else {
      // 新增模式，重置表单
      formRef.value?.resetFields();
    }
  }
});

// 处理确定
const handleOk = async () => {
  try {
    const values = await formRef.value?.validate();
    if (values) {
      submitLoading.value = true;
      
      // 处理省市数据
      if (values.region?.length === 2) {
        values.province = values.region[0];
        values.city = values.region[1];
      }
      delete values.region;

      if (props.contact?.id) {
        // 编辑
        await updateContact({
          id: props.contact.id,
          customerId: props.customerId!,
          ...values
        });
        message.success('编辑成功');
      } else {
        // 新增
        await createContact({
          customerId: props.customerId!,
          ...values
        });
        message.success('创建成功');
      }
      
      emit('success');
      handleCancel();
    }
  } catch (error) {
    console.error('提交失败:', error);
    message.error('提交失败');
  } finally {
    submitLoading.value = false;
  }
};

// 处理取消
const handleCancel = () => {
  emit('update:visible', false);
  formRef.value?.resetFields();
};
</script> 